#include "lasso.hh"
#include <string>
#include <iostream>
#include <fstream>

int main(const int argc, const char* argv[])
{
  if (argc < 3)
  {
    std::cerr << argv[0] << " x_file y_file [output]" << std::endl;
    return -1;
  }

  const char* x_file = argv[1];
  const char* y_file = argv[2];
  std::string output("output");

  if (argc > 3)
    output = argv[3];

  expr_lm_vec_t data_vec;
  size_t n, p;

  if (!read_expr_lm_vec(x_file, y_file, data_vec, n, p))
    return -1;

  TLOG("READ data n = " << n << " p = " << p);

  expr_lm_set_t data_set;

  for (size_t i = 0; i < n; ++i)
    data_set.insert(data_vec[i]);

  func_lasso_t lasso(p);

  double tol = 1e-4;
  size_t max_iter = 1000;

  TLOG("FIT lasso object to data");
  for (size_t iter = 0; iter < max_iter; ++iter)
  {
    lasso.update(data_set);

    double delt = empirical_bayes(lasso);
#ifdef DEBUG
    std::cerr << "\r" << "iter = " << iter << " delt = " << delt << std::endl;
#endif
    if (delt < tol)
      break;
  }

  {
    std::ofstream ofs((output + ".beta").c_str(), std::ios::out);
    lasso.write_beta(ofs);
    ofs.close();
  }

  {
    std::ofstream ofs((output + ".sd").c_str(), std::ios::out);
    lasso.write_sd(ofs);
    ofs.close();
  }

  {
    std::ofstream ofs((output + ".cov").c_str(), std::ios::out);
    lasso.write_prec(ofs);
    ofs.close();
  }

  return 0;
}
